import React from 'react';
import { connect } from 'dva';
import { Helmet } from "react-helmet";
import { WhiteSpace,Toast, Icon } from 'antd-mobile';
import Container from '../components/Base/Container';
import { routerRedux } from 'dva/router';
import styles from './ShopsDistance.less';
import WxLocation from "../components/location/WxLocation";
import BaiduLocation from "../components/location/BaiduLocation";

let map;
const defaultDistance = 99999999999999999999999999999999999999999999999;

let location;


//latitude 纬度，longitude 经度

const rad = (d) => {
  return d * Math.PI / 180.0;//经纬度转换成三角函数中度分表形式。
};

/**
 * 参入两个坐标，
 * @param lng1
 * @param lat1
 * @param lng2
 * @param lat2
 * @returns {number} 两点之间的公里
 */
const calcDistance = (lng1, lat1, lng2, lat2) => {
  var radLat1 = rad(lat1);
  var radLat2 = rad(lat2);
  var a = radLat1 - radLat2;
  var b = rad(lng1) - rad(lng2);
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
  s = s * 6378.137;
  // EARTH_RADIUS;
  s = Math.round(s * 10000) / 10;
  return s;
};

class ShopsDistance extends React.Component {

  state={
    currentLocation: [],
    dis: ''
  };

  componentDidMount() {
    var ua = window.navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i) == 'micromessenger'){
      location = new WxLocation();
    } else {
      location = new BaiduLocation();
    }
    location.getLocation().then(res => {
      this.setState({
        currentLocation: [
          res.longitude,
          res.latitude,
        ]
      });
    });
  }

  goTo = item => {
    const dis = this.state.dis
    if (!(item.location && item.location.length === 2)) {
      Toast.fail('该门店未设置坐标', 2000);
      return;
    }
    location.openLocation(item.location['0'], item.location['1'], item.branch_name, item.qez_address, () => {
      this.props.dispatch(routerRedux.push({
        pathname: '/shopsMap',
        /* query里面只能传字符串 */
        query: {
          shopId: this.props.location.query.shopId,
          shopid: this.props.location.query.shopid,
          branch_no: item.branch_no,
          branch: JSON.stringify(item)
        },
      }));
    })
  };

  branchList=() => {
    let list = [];
    this.props.branchList.map((item) => {
      const obj = Object.assign({}, item);

      if (this.state.currentLocation.length > 0) {
        obj.distance = calcDistance(item.location['0'], item.location['1'], this.state.currentLocation[0], this.state.currentLocation[1]);
      } else {
        obj.distance = defaultDistance;
      }
      list.push(obj);
    });

    list = list.sort((item1, item2) => {
      return item1.distance - item2.distance;
    });
    
    const arr = list.map(item => {
      let c = this.state.currentLocation.length ? (item.distance !== defaultDistance ? (item.distance < 1000 ? `${item.distance}m` : `${(item.distance / 1000).toFixed(2)}km`) : '') : ''
      return (
      <div className={styles["item-list"]} key={item.branch_no}>
        <div className={styles["item-maja"]}>
          <div className={styles["item-context"]}>

            <div className={styles["item-img"]} style={{ backgroundImage: `url(${item.qez_pic && item.qez_pic[0] ? item.qez_pic[0] : require('../assets/no_image.jpg')})` }} />
           
            <div className={styles["item-right"]}>
            <span className={styles["shop-title"]}>
              {item.branch_name}
              <span className={styles.dis}>
                {this.state.currentLocation.length ? (item.distance !== defaultDistance ? (item.distance < 1000 ? `${item.distance}m` : `${(item.distance / 1000).toFixed(2)}km`) : '') : ''}
              </span>
            </span>

           <div className={styles['location']}>
           {item.qez_address &&
            <span className={styles["shop-location"]} onClick={this.goTo.bind(this, {...item, dis:c})}>
              <img className={styles.icon} src={require('../assets/map.png')} alt="" />
              { item.qez_address }
            </span>
            }
           </div>
           
           <div className={styles['contactMe']}>
           {item.qez_tel &&
            <span className={styles["shop-phone"]}>
              <img className={styles.icon} src={require('../assets/tel.png')} />
              {item.qez_tel}</span>
            }
            {item.qez_tel &&
            <a href={`tel:${item.qez_tel}`} className={styles.btn}>联系门店</a>
            }
           </div>
            </div>

          </div>
        </div>
      </div>
    )
  });

    return arr;
  };

  clickTel=(tel, e) => {
    e.stopPropagation();
    location.href = `tel:${tel}`;
  };

  render() {
    return (
      <Container className="couponContainer" title="附近的门店" >
        <Helmet>
          <title>附近的门店</title>
        </Helmet>
        <div className={styles['storeWrap']}>
          <div className={styles['store']}>
            <span onClick={() => this.props.history.goBack()}><Icon key="1"  size="md" type="left" /></span>
            <span>附近的门店</span>
          </div>
        </div>
        <div style={{ backgroundColor: 'white', marginTop: '1.062802rem' }}>
          { this.branchList() }
        </div>
      </Container>
    );
  }
}

export default connect((state) => {
  return {
    branchList: state.stat.branchList,
  };
})(ShopsDistance);
